package com.naml.c_exit;

/**
 * @author marin
 * @version 1.0
 * @date 2025/4/26 17:37
 * @desc  演示线程终止操作--定义一个变量
 */
@SuppressWarnings("all")
public class ThreadExit01 {
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();

        for (int i = 0; i < 20; i++) {
            try {
                System.out.println(Thread.currentThread().getName()+"输出:" + i);
                Thread.sleep(1000);
                if (i == 10){
                    System.out.println("主线程休眠10s，准备终止子线程...");
                    Thread.sleep(10000);
                    thread.setFlag(false);
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

@SuppressWarnings("all")
class MyThread extends Thread {

    //定义一个终止变量
    private static boolean  flag = true;

    public static void setFlag(boolean flag) {
        MyThread.flag = flag;
    }

    @Override
    public void run() {
        while (flag) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread().getName()+"还在运行中...");
        }
    }
}